﻿using Terraria.ID;
using Terraria;
using Terraria.ModLoader;
using Microsoft.Xna.Framework;
using EAMF.Content.Projectiles;
using Microsoft.Xna.Framework.Graphics;

namespace EAMF.Content.NPCs.Monster
{
    //飞盘
    public class Frisbee : ModNPC
    {
        //状态
        public enum ActionState
        {
            Sleep,
            Move,
            QuickMove,
            Shoot
        }
        //旧位置
        private Vector2[] oldPosi = new Vector2[5];
        //状态
        public ref float AI_State => ref NPC.ai[0];
        //计时器
        public ref float AI_Timer => ref NPC.ai[1];
        
        //
        public override void SetStaticDefaults()
        {
            Main.npcFrameCount[NPC.type] = 4; //设置npc的帧数
            //NPCID.Sets.TrailingMode[Type] = 2; //设置模式
            //NPCID.Sets.TrailCacheLength[Type] = 100; //设置记录帧数
            ProjectileID.Sets.DrawScreenCheckFluff[Type] = 2000;
        }
        public override void SetDefaults()
        {
            NPC.width = 51;
            NPC.height = 63;
            NPC.damage = 1;
            NPC.lifeMax = 500;
            NPC.defense = 10;
            NPC.knockBackResist = 0.3f; //被击退能力
            NPC.HitSound = SoundID.NPCHit4;
            NPC.DeathSound = SoundID.NPCDeath14;
            NPC.value = Item.buyPrice(0, 1, 0, 0);
            NPC.noGravity = true; //是否不受重力影响
            NPC.noTileCollide = false;//是否可以穿墙
        }
        /// <summary>
        /// 高级绘制
        /// </summary>
        /// <param name="spriteBatch"></param>
        /// <param name="screenPos">屏幕左上角的世界坐标</param>
        /// <param name="drawColor"></param>
        /// <returns></returns>
        public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
        {
            if (AI_State == (float)ActionState.QuickMove)
            {
                //当他处于快速移动时
                Texture2D texture2D = ModContent.Request<Texture2D>("../Frisbee").Value;
                //得到材质
                Rectangle rectangle = new Rectangle( //计算扣取的大小和位置
                    0, //这个框左上角的水平坐标,代表从帧图上哪个位置开始抠图
                    0, //框左上角的纵坐标
                    texture2D.Width, //框的宽度
                    texture2D.Height / Main.npcFrameCount[Type] //框的高度,材质的高度除以帧数便可以得到
                );
                for (int i = oldPosi.Length - 1; i > 0; i--)
                {
                    float factor = 1 - (float)i / ProjectileID.Sets.TrailCacheLength[Type];
                    Vector2 vector1 = oldPosi[i] - screenPos + new Vector2(0, 4); //10 * i * NPC.velocity.SafeNormalize(Vector2.Zero)

                    //从最老的开始绘制
                    spriteBatch.Draw(
                        texture2D,
                        vector1,
                        rectangle,
                        drawColor * factor,
                        0,
                        new Vector2(texture2D.Width / 2, texture2D.Height / Main.npcFrameCount[Type] / 2),
                        new Vector2(1, 1),
                        SpriteEffects.None,
                        0
                        );
                }
                //for (int i = NPCID.Sets.TrailCacheLength[Type] - 1; i > 0; i--)
                //{
                //    float factor = 1 - (float)i / ProjectileID.Sets.TrailCacheLength[Type];
                //    Vector2 vector1 = NPC.oldPos[3] - screenPos + new Vector2(NPC.width / 2, NPC.height / 2 + 4); //10 * i * NPC.velocity.SafeNormalize(Vector2.Zero)

                //    //从最老的开始绘制
                //    spriteBatch.Draw(
                //        texture2D,
                //        vector1,
                //        NPC.frame,
                //        drawColor * factor,
                //       (NPC.oldPos[i - 1] - NPC.oldPos[i]).ToRotation(),
                //        new Vector2(texture2D.Width / 2, texture2D.Height / Main.npcFrameCount[Type] / 2),
                //        new Vector2(1, 1),
                //        SpriteEffects.None,
                //        0
                //        );

            }
            return base.PreDraw(spriteBatch, screenPos, drawColor);
            //return false;
        }

        /// <summary>
        /// 根据NPC的状态做帧循环
        /// </summary>
        /// <param name="frameHeight"></param>
        public override void FindFrame(int frameHeight)
        {
            NPC.spriteDirection = NPC.direction;
            int startFrame = 0;
            int finalFrame = 2;
            if (AI_State == (float)ActionState.Sleep || AI_State == (float)ActionState.Move || AI_State == (float)ActionState.QuickMove)
            {
                int frameSpeed = 5;
                NPC.frameCounter += 0.5f;
                NPC.frameCounter += NPC.velocity.Length() / 10f; // Make the counter go faster with more movement speed
                if (NPC.frameCounter > frameSpeed)
                {
                    NPC.frameCounter = 0;
                    NPC.frame.Y += frameHeight;

                    if (NPC.frame.Y > finalFrame * frameHeight)
                    {
                        NPC.frame.Y = startFrame * frameHeight;
                    }
                }
            }
            if (AI_State == (float)ActionState.Shoot)
            {
                NPC.frame.Y = (int)ActionState.Shoot * frameHeight;
            }
        }
        public override void AI()
        {
            NPCList.Push(NPC.Center, ref oldPosi);
            if (AI_State == (float)ActionState.Sleep)
            {
                Sleep();
            }
            if (AI_State == (float)ActionState.Move)
            {
                Move();
                //当为移动状态时
            }
            if (AI_State == (float)ActionState.QuickMove)
            {
                QuickMove();
            }
            if (AI_State == (float)ActionState.Shoot)
            {
                //当为射击状态时
                Shoot();
            }
        }
        public void Sleep()
        {
            //当为休息状态时,对附近的敌人进行侦测，当目标到达范围内时触发
            NPC.TargetClosest(true); //这句会自动搜索最近的玩家
            if (NPC.HasPlayerTarget && Main.player[NPC.target].Distance(NPC.Center) < 1500f)
            {
                //到达此范围内时进行
                AI_State = (float)ActionState.Move;
                AI_Timer = 0;
            }
        }
        public void Move()
        {
            AI_Timer++;
            if (AI_Timer == 1)
            {
                NPC.velocity = 3 * ((Main.player[NPC.target].Center - NPC.Center).SafeNormalize(Vector2.Zero) + new Vector2(NPC.direction * 2, -0.2f));
            }
            //四十帧后切换状态，或者玩家靠得太近
            else if (AI_Timer > 200 || NPC.HasPlayerTarget && Main.player[NPC.target].Distance(NPC.Center) < 100f)
            {
                AI_State = (float)ActionState.QuickMove;
                AI_Timer = 0;
            }
        }
        public void QuickMove()
        {
            AI_Timer++;
            if (AI_Timer == 1)
            {
                NPC.velocity = 25 * (NPC.Center - Main.player[NPC.target].Center).SafeNormalize(Vector2.Zero);
            }
            else if (AI_Timer > 5)
            {
                //快速移动完毕后切换状态
                AI_State = (float)ActionState.Shoot;
                AI_Timer = 0;
            }
        }
        public void Shoot()
        {
            AI_Timer++;
            if (AI_Timer == 1)
            {
                NPC.velocity = Vector2.Zero;
            }
            if (AI_Timer % 5 == 1) //每5帧发射一次s
            {
                //弹幕，发射一串速度与方向有偏转的弹幕,Main.rand.Next(-10, 10)
                Vector2 position = 200 * (Main.player[NPC.target].Center - NPC.Center).SafeNormalize(Vector2.Zero);//npc指向玩家的向量
                position += new Vector2(Main.rand.Next(-10, 10), Main.rand.Next(-10, 10)); //添加10个像素的偏转
                position = Main.rand.Next(12, 15) * position.SafeNormalize(Vector2.Zero);//速度修正
                int type = ModContent.ProjectileType<NanoBullet>();
                var entitySource = NPC.GetSource_FromAI();
                Projectile.NewProjectile(entitySource, NPC.Center, position, type, 1, 6, Main.myPlayer);
                //IEntitySource spawnSource 不知
                //Vector2 position 弹幕发射位置
                //Vector2 velocity 弹幕的速度
                //int Type 弹幕id
                //int Damage 弹幕伤害
                //float KnockBack 弹幕击退能力
                //int Owner = -1 //不知
            }
            if (AI_Timer > 100)
            {
                //重新回到初始状态
                AI_State = (float)ActionState.Sleep;
                AI_Timer = 0;
            }

        }
        //设置生成方式和概率
        public override float SpawnChance(NPCSpawnInfo spawnInfo)
        {
            if (spawnInfo.Player.ZoneOverworldHeight) //当玩家处于高处时
            {
                return 0.2f;
            }
            if (spawnInfo.Player.ZoneSkyHeight) //当玩家处于太空时
            {
                return 0.5f;
            }
            return 0f;
        }
    }
}
